/*****************************************************************************
 *  CommLayerLib for J2ME - TCPClient.java
 *  Copyright (C) 2012  Matteo Piscitelli
 *  E-mail: matteo@picciux.it
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  For further info, check http://code.google.com/p/java-comm-layer/
 *
 *  SVN: $Id: TCPClient.java 40 2012-10-10 19:54:31Z picciux@gmail.com $
 *  
 *****************************************************************************/

package it.picciux.commlayer.j2me.net;

import it.picciux.commlayer.CommLayerException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;

/**
 * TCPClient fro J2ME
 * @author Matteo Piscitelli
 *
 */
public class TCPClient extends it.picciux.commlayer.net.TCPClient {
	protected SocketConnection sock;
	
	/**
	 * 
	 */
	public TCPClient() {
		super();
		sock = null;
	}

	/**
	 * 
	 */
	public TCPClient(SocketConnection socketConnection) {
		super();
		sock = socketConnection;
	}
		
	protected void setConnectThread(Thread t) { return;	}
	protected void setReaderThread(Thread t) { return; }

	protected void retrieveRemoteAddress() {
		try {
			address = sock.getAddress();
			port = sock.getPort();
		} catch (IOException e) {
			address = "";
			port = 0;
		}
	}

	public void disconnect() {
		connected = false;
		if (sock != null) try { sock.close(); } catch (IOException e) {}
	}

	protected boolean tryConnection() throws CommLayerException {
		try {
			sock = (SocketConnection) Connector.open("socket://" + address + ":" + Integer.toString(port));
		} catch (IOException e) {
			throw new CommLayerException(e.getMessage(), NetworkLayer.CONNECTION_ERROR);
		}
		return true;
	}

	protected void destroy() {
		try { sock.close(); } catch (Exception e) {}	
		sock = null;
	}

	public InputStream getInputStream() throws IOException {
		if (sock == null) throw new IOException("Socket null");
		return sock.openInputStream();
	}

	public OutputStream getOutputStream() throws IOException {
		if (sock == null) throw new IOException("Socket null");
		return sock.openOutputStream();
	}

}
